"""
高并发测试
因为CPython的多线程是假的, 所以这里使用了 gevent + requests的方案
"""

import time
import requests
import gevent
from gevent import monkey

monkey.patch_all()


def request_event():
    """模拟请求事件"""
    url = 'http://127.0.0.1:8888/blog/articles/'
    access_token = """eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiZXhwIjoxNjI2NzY5NTIyLCJqdGkiOiI3YzUxNmQ2OTQ5NGU0MzVlOTY5YWIyYmYzYmI3MDdiMSIsInVzZXJfaWQiOjF9.Idzn6p7VtDbtVmE0v3jfiOmhRUn9b4cRDjU3rYPv-1U"""
    headers = {"Authorization": "Bearer " + access_token}
    print('start...')
    response = requests.get(url=url, headers=headers)
    print(response.status_code, response.ok)


def gevent_demo(n):
    """模拟高并发"""

    print('event spawning...')
    event_list = []

    for i in range(n):
        event = gevent.spawn(request_event)
        event_list.append(event)

    begin_time = time.time()
    print('event spawned', begin_time)
    gevent.joinall(event_list)  # 开始
    end_time = time.time()
    print('event finish', end_time)
    print('avg:', (end_time - begin_time) / n)
    print('sum:', end_time - begin_time)


if __name__ == '__main__':
    x = 500
    # x =  510 509是极限510系统会崩
    gevent_demo(x)
